class Solution:
    def myAtoi(self, str: str) -> int:
        str = str.strip()
        if str == "":
            return 0
        isNegative = False
        finalStr = ''
        num = 0
        if str[0] == '-':
            isNegative = True
            str = str.replace('-', '', 1)
        elif str[0] == '+':
            isNegative = False
            str = str.replace('+', '', 1)
        elif not str[0].isdigit():
            return 0
        for s in str:
            if s.isdigit():
                finalStr += s
            elif s == ".":
                break
            else:
                break
        if finalStr.isdigit():
            if isNegative:
                num = -int(finalStr)
            else:
                num = int(finalStr)
        else:
            num = 0
        if num < -(2 ** 31):
            num = -(2 ** 31)
        elif num > (2 ** 31) - 1:
            num = (2 ** 31) - 1
        return num


solution = Solution()

print(solution.myAtoi("++2"))

# Success
# Runtime: 44 ms, faster than 88.30% of Python3 online submissions for String to Integer (atoi).
# Memory Usage: 13.1 MB, less than 84.19% of Python3 online submissions for String to Integer (atoi).

# 用了接近2个小时的时间A这道题，主要考虑的情况很多，从if..else的数量可以看出。

# 超越95.72%的解:
# class Solution:
#     def myAtoi(self, s: str) -> int:
#         def isdigit(x):
#             return '0' <= x <= '9'
#
#         def issign(x):
#             return x == '-' or x == '+'
#
#         s = s.strip()
#         if not s or not (isdigit(s[0]) or issign(s[0])):
#             return 0
#
#         i = 1
#         while i < len(s) and isdigit(s[i]):
#             i += 1
#         if i == 1 and issign(s[0]):
#             return 0
#
#         INT_MIN, INT_MAX = -2 ** 31, 2 ** 31 - 1
#         return max(INT_MIN, min(int(s[:i]), INT_MAX))
